<template>
  <div class="dashboard-page">
    <!-- 添加粒子背景 -->
    <div class="particles-container">
      <div v-for="n in 30" :key="n" class="particle" :style="{ 
        '--delay': `${Math.random() * 5}s`,
        '--duration': `${Math.random() * 10 + 10}s`,
        '--position': `${Math.random() * 100}%`,
        '--size': `${Math.random() * 30 + 10}px`
      }"></div>
    </div>
    
    <div class="page-title-section">
      <div class="magical-underline"></div>
      <h1 class="magical-title">学信链系统</h1>
      <div class="title-decoration left"></div>
      <div class="title-decoration right"></div>
    </div>
    
    <!-- 统计卡片 -->
    <dashboard-stats></dashboard-stats>
    
    <div class="dashboard-content">
      <!-- 左侧主要内容区 -->
      <div class="main-content">
        <el-card class="operation-log-card">
          <div class="card-glow-effect"></div>
          <template #header>
            <div class="card-header">
              <div class="card-title">
                <i class="el-icon-data-line"></i>
                <span>系统操作日志</span>
              </div>
              <el-button type="primary" size="small" @click="refreshActivityLog" plain class="refresh-button">
                <i class="el-icon-refresh"></i> 刷新
              </el-button>
            </div>
          </template>
          
          <!-- 使用系统操作日志组件 -->
          <system-operation-log ref="logComponent" :limit="10" />
        </el-card>
      </div>
      
      <!-- 右侧边栏 -->
      <div class="side-content">
        <el-card class="blockchain-info-card">
          <template #header>
            <div class="card-header">
              <div class="card-title">
                <i class="el-icon-link"></i>
                <span>区块链状态</span>
              </div>
            </div>
          </template>
          
          <div class="blockchain-status">
            <div class="status-item">
              <div class="status-label">网络状态</div>
              <div class="status-value">
                <div class="status-dot online"></div>
                <span>连接正常</span>
              </div>
            </div>
            <div class="status-item">
              <div class="status-label">最新区块</div>
              <div class="status-value">#{{ blockchainInfo.latestBlock }}</div>
            </div>
            <div class="status-item">
              <div class="status-label">Gas价格</div>
              <div class="status-value">{{ blockchainInfo.gasPrice }} Gwei</div>
            </div>
            <div class="status-item">
              <div class="status-label">合约地址</div>
              <div class="status-value address">{{ truncateAddress(blockchainInfo.contractAddress) }}
                <el-tooltip content="复制地址" placement="top">
                  <i class="el-icon-copy-document" @click="copyAddress(blockchainInfo.contractAddress)"></i>
                </el-tooltip>
              </div>
            </div>
          </div>
        </el-card>
        
        <el-card class="system-info-card">
          <template #header>
            <div class="card-header">
              <div class="card-title">
                <i class="el-icon-info"></i>
                <span>系统信息</span>
              </div>
            </div>
          </template>
          
          <div class="system-info">
            <div class="info-item">
              <div class="info-label">管理员账户</div>
              <div class="info-value">{{ truncateAddress(adminAddress) }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">系统名称</div>
              <div class="info-value">学信链</div>
            </div>
            <div class="info-item">
              <div class="info-label">版本号</div>
              <div class="info-value">v1.2.0</div>
            </div>
            <div class="info-item">
              <div class="info-label">上次更新</div>
              <div class="info-value">{{ formatDate(systemInfo.lastUpdate) }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">证书总数</div>
              <div class="info-value">{{ totalStats.certificates }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">学生总数</div>
              <div class="info-value">{{ totalStats.students }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">今日操作数</div>
              <div class="info-value highlight">{{ totalStats.todayOperations }}</div>
            </div>
          </div>
        </el-card>
        
        <el-card class="quick-actions-card">
          <template #header>
            <div class="card-header">
              <div class="card-title">
                <i class="el-icon-menu"></i>
                <span>快捷操作</span>
              </div>
            </div>
          </template>
          
          <div class="quick-actions">
            <el-button type="primary" @click="handleAction('certificate')">
              <i class="el-icon-plus"></i> 颁发证书
            </el-button>
            <el-button type="success" @click="handleAction('student')">
              <i class="el-icon-user"></i> 添加学生
            </el-button>
            <el-button type="info" @click="handleAction('export')">
              <i class="el-icon-download"></i> 导出数据
            </el-button>
            <el-button type="warning" @click="handleAction('settings')">
              <i class="el-icon-setting"></i> 系统设置
            </el-button>
          </div>
        </el-card>
      </div>
    </div>
    <div class="dashboard-footer">
      <p>© {{ new Date().getFullYear() }} 学信链证书管理系统 - 版权所有</p>
    </div>
  </div>
</template>

<script>
import { reactive, onMounted, computed, ref, onUnmounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import DashboardStats from '@/components/DashboardStats.vue'
import SystemOperationLog from '@/components/SystemOperationLog.vue'
import LogService from '@/store/logService'

export default {
  name: 'SystemDashboard',
  components: {
    DashboardStats,
    SystemOperationLog
  },
  setup() {
    const store = useStore()
    const router = useRouter()
    const logComponent = ref(null)
    
    // 区块链信息
    const blockchainInfo = reactive({
      latestBlock: 12345678,
      gasPrice: 25,
      contractAddress: '0x1234567890abcdef1234567890abcdef12345678'
    })
    
    // 系统信息
    const systemInfo = reactive({
      lastUpdate: new Date('2024-06-01T10:30:00')
    })
    
    // 统计信息
    const totalStats = reactive({
      certificates: 0,
      students: 0,
      todayOperations: 0
    })
    
    // 管理员地址
    const adminAddress = computed(() => {
      return store.state.adminAddress || '0xabcdef1234567890abcdef1234567890abcdef12'
    })
    
    // 刷新操作日志
    const refreshActivityLog = () => {
      if (logComponent.value) {
        logComponent.value.refreshLogs()
        
        // 更新统计数据
        countTodayOperations()
        fetchStats()
      }
    }
    
    // 快捷操作处理
    const handleAction = (actionType) => {
      switch (actionType) {
        case 'certificate':
          // 记录操作日志
          LogService.logSystemOperation('访问颁发证书页面')
          // 导航到证书页面
          router.push('/certificates')
          break
        case 'student':
          // 记录操作日志
          LogService.logSystemOperation('访问添加学生页面')
          // 导航到学生页面
          router.push('/students')
          break
        case 'export':
          // 记录操作日志
          LogService.logSystemOperation('导出系统数据')
          ElMessage.success('数据导出功能即将推出')
          break
        case 'settings':
          // 记录操作日志
          LogService.logSystemOperation('访问系统设置')
          ElMessage.info('系统设置功能即将推出')
          break
      }
    }
    
    // 获取证书和学生统计数据
    const fetchStats = async () => {
      try {
        // 获取证书数量
        const certificates = store.state.certificates || []
        totalStats.certificates = certificates.length
        
        // 获取学生数量
        const students = store.state.students || []
        totalStats.students = students.length
        
        // 如果store中没有数据，尝试从API获取
        if (certificates.length === 0) {
          await store.dispatch('fetchCertificates')
          totalStats.certificates = store.state.certificates.length
        }
        
        if (students.length === 0) {
          await store.dispatch('fetchStudents')
          totalStats.students = store.state.students.length
        }
      } catch (error) {
        console.error('获取统计数据失败:', error)
      }
    }
    
    // 计算今日操作数
    const countTodayOperations = () => {
      const logs = LogService.getLogs()
      const today = new Date()
      today.setHours(0, 0, 0, 0)
      
      // 统计今天的操作数
      const todayLogs = logs.filter(log => {
        const logDate = new Date(log.timestamp)
        return logDate >= today
      })
      
      totalStats.todayOperations = todayLogs.length
    }
    
    // 格式化日期
    const formatDate = (date) => {
      if (!date) return '未知'
      const d = new Date(date)
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
    }
    
    // 截断地址显示
    const truncateAddress = (address) => {
      if (!address) return '';
      return `${address.substring(0, 6)}...${address.substring(address.length - 4)}`;
    }
    
    // 复制地址
    const copyAddress = (address) => {
      navigator.clipboard.writeText(address).then(() => {
        ElMessage.success('地址已复制到剪贴板');
        // 记录日志
        LogService.logSystemOperation('复制合约地址', { address })
      }).catch(err => {
        console.error('复制失败:', err);
        ElMessage.error('复制失败');
      });
    }
    
    // 添加实时监听系统日志变化的功能
    const setupLogWatcher = () => {
      // 使用定时器每10秒检查一次日志更新
      const logWatchInterval = setInterval(() => {
        refreshActivityLog()
      }, 10000)
      
      // 在组件卸载时清除定时器
      onUnmounted(() => {
        clearInterval(logWatchInterval)
      })
    }
    
    // 初始化
    onMounted(() => {
      // 记录系统操作日志
      LogService.logSystemOperation('访问系统仪表盘')
      
      // 获取证书和学生数量
      fetchStats()
      
      // 计算今日操作数
      countTodayOperations()
      
      // 设置日志监听
      setupLogWatcher()
    })
    
    return {
      blockchainInfo,
      systemInfo,
      adminAddress,
      totalStats,
      logComponent,
      refreshActivityLog,
      handleAction,
      formatDate,
      truncateAddress,
      copyAddress
    }
  }
}
</script>

<style scoped>
.dashboard-page {
  max-width: 1200px;
  margin: 30px auto;
  padding: 0 20px;
  position: relative;
  overflow: hidden;
}

/* 粒子背景效果 */
.particles-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  overflow: hidden;
  pointer-events: none;
}

.particle {
  position: absolute;
  width: var(--size);
  height: var(--size);
  background: radial-gradient(circle, rgba(97, 73, 205, 0.6) 0%, rgba(97, 73, 205, 0) 70%);
  border-radius: 50%;
  top: calc(var(--position) - 50px);
  left: calc(var(--position) - 50px);
  animation: float var(--duration) ease-in-out var(--delay) infinite;
  opacity: 0.4;
  filter: blur(8px);
}

.particle:nth-child(even) {
  background: radial-gradient(circle, rgba(52, 179, 241, 0.6) 0%, rgba(52, 179, 241, 0) 70%);
}

.particle:nth-child(3n) {
  background: radial-gradient(circle, rgba(103, 194, 58, 0.4) 0%, rgba(103, 194, 58, 0) 70%);
}

/* 页面标题区样式 */
.page-title-section {
  text-align: center;
  margin-bottom: 35px;
  position: relative;
  padding: 20px 0;
}

.magical-title {
  font-size: 36px;
  font-weight: 700;
  color: transparent;
  background: linear-gradient(45deg, #34b3f1, #6149cd, #6149cd, #34b3f1);
  background-size: 300% 300%;
  background-clip: text;
  -webkit-background-clip: text;
  animation: gradientText 6s ease infinite;
  position: relative;
  display: inline-block;
  margin: 0;
  letter-spacing: 2px;
  text-shadow: 0 10px 20px rgba(97, 73, 205, 0.15);
}

@keyframes gradientText {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

.magical-underline {
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
  width: 220px;
  height: 3px;
  background: linear-gradient(90deg, rgba(97,73,205,0) 0%, rgba(97,73,205,1) 50%, rgba(97,73,205,0) 100%);
  box-shadow: 0 4px 8px rgba(97, 73, 205, 0.3);
}

/* 内容布局 */
.dashboard-content {
  display: grid;
  grid-template-columns: 1fr 350px;
  gap: 24px;
  margin-top: 30px;
}

.main-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.side-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 操作日志卡片样式 */
.operation-log-card {
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
}

.operation-log-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(97, 73, 205, 0.1);
}

.card-glow-effect {
  position: absolute;
  top: -50%;
  right: -50%;
  width: 200px;
  height: 200px;
  background: radial-gradient(circle, rgba(97, 73, 205, 0.08) 0%, rgba(97, 73, 205, 0) 70%);
  border-radius: 50%;
  pointer-events: none;
  z-index: 0;
}

.refresh-button {
  position: relative;
  overflow: hidden;
  background: linear-gradient(45deg, rgba(52, 179, 241, 0.1), rgba(97, 73, 205, 0.1));
  border: 1px solid rgba(97, 73, 205, 0.2);
  transition: all 0.3s;
}

.refresh-button:hover {
  background: linear-gradient(45deg, rgba(52, 179, 241, 0.2), rgba(97, 73, 205, 0.2));
  transform: translateY(-2px);
  box-shadow: 0 5px 10px rgba(97, 73, 205, 0.1);
}

.refresh-button i {
  margin-right: 5px;
  transition: transform 0.5s;
}

.refresh-button:hover i {
  transform: rotate(180deg);
}

/* 卡片样式 */
:deep(.el-card) {
  border-radius: 16px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.06);
  border: none;
  overflow: hidden;
  transition: all 0.3s ease;
  background-color: rgba(255, 255, 255, 0.96);
  backdrop-filter: blur(10px);
}

:deep(.el-card:hover) {
  box-shadow: 0 15px 35px rgba(97, 73, 205, 0.15);
}

:deep(.el-card__header) {
  padding: 18px 20px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  position: relative;
}

:deep(.el-card__header)::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 1px;
  background: linear-gradient(90deg, 
    rgba(97,73,205,0) 0%, 
    rgba(97,73,205,0.3) 50%, 
    rgba(97,73,205,0) 100%
  );
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  position: relative;
}

.card-title::before {
  content: "";
  position: absolute;
  left: -10px;
  top: 50%;
  transform: translateY(-50%);
  width: 3px;
  height: 18px;
  background: linear-gradient(180deg, #6149cd, #3498db);
  border-radius: 3px;
}

.card-title i {
  margin-right: 10px;
  font-size: 20px;
  background: linear-gradient(135deg, #6149cd, #3498db);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  animation: floatIcon 3s ease-in-out infinite;
}

@keyframes floatIcon {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-5px); }
}

/* 区块链状态卡片 */
.blockchain-status {
  padding: 10px 0;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px dashed rgba(0, 0, 0, 0.05);
}

.status-item:last-child {
  border-bottom: none;
}

.status-label {
  color: #909399;
  font-size: 14px;
}

.status-value {
  font-weight: 500;
  color: #303133;
  display: flex;
  align-items: center;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 6px;
}

.status-dot.online {
  background-color: #67c23a;
  box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.2);
}

.status-value.address {
  font-family: monospace;
  font-size: 14px;
}

.status-value i {
  margin-left: 8px;
  color: #909399;
  cursor: pointer;
  transition: all 0.3s;
}

.status-value i:hover {
  color: #6149cd;
}

/* 系统信息卡片 */
.system-info {
  padding: 10px 0;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px dashed rgba(0, 0, 0, 0.05);
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  color: #909399;
  font-size: 14px;
}

.info-value {
  font-weight: 500;
  color: #303133;
}

.info-value.highlight {
  color: #f56c6c;
  font-weight: 700;
}

/* 快捷操作卡片 */
.quick-actions {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  padding: 10px 0;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .dashboard-content {
    grid-template-columns: 1fr;
  }
  
  .side-content {
    display: grid;
    grid-template-columns: 1fr 1fr;
  }
  
  .quick-actions-card {
    grid-column: 1 / 3;
  }
}

@media (max-width: 768px) {
  .side-content {
    grid-template-columns: 1fr;
  }
  
  .quick-actions-card {
    grid-column: auto;
  }
  
  .magical-title {
    font-size: 28px;
  }
  
  .dashboard-page {
    padding: 0 15px;
  }
  
  .quick-actions {
    grid-template-columns: 1fr;
  }
}

.dashboard-footer {
  text-align: center;
  margin-top: 40px;
  padding: 20px 0;
  color: #94a3b8;
  font-size: 14px;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
}
</style> 